package com.view.adminMenu;

import com.run.UserRun;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.SQLException;

public class myInfoMenu {
    private JLabel usernameLabel = new JLabel("账号");
    private JLabel passwordLabel = new JLabel("密码");
    private JButton changePasswordButton  = new JButton("修改密码");
    private Box usernameBox = Box.createHorizontalBox();
    private Box passwordBox = Box.createHorizontalBox();
    private Box mainBox = Box.createHorizontalBox();

    private String newPassword = null;

    public JPanel init(JFrame jFrame,String username,String password) {
        JPanel mainPanel = new JPanel();

        JLabel USERNAME = new JLabel(username);
        JLabel PASSWORD = new JLabel(password);

        usernameBox.add(Box.createHorizontalStrut(80));
        usernameBox.add(usernameLabel);
        usernameBox.add(Box.createHorizontalStrut(20));
        usernameBox.add(USERNAME);
        usernameBox.add(Box.createHorizontalStrut(100));
        passwordBox.add(Box.createHorizontalStrut(80));
        passwordBox.add(passwordLabel);
        passwordBox.add(Box.createHorizontalStrut(20));
        passwordBox.add(PASSWORD);
        passwordBox.add(Box.createHorizontalStrut(20));
        passwordBox.add(changePasswordButton);

        mainBox.add(usernameBox);
        mainBox.add(passwordBox);

        mainPanel.add(mainBox);

        changePasswordButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                newPassword = JOptionPane.showInputDialog(jFrame,"新密码:");
                System.out.println(newPassword);
                Connection conn = null;
                boolean isChanged = false;
                try {
                    conn = com.util.DBUtil.getConnection();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                try {
                    isChanged = new UserRun().changePassword(conn,username,password,"manager",newPassword);
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
                if(isChanged == false) {
                    System.out.println("密码修改失败");
                    JOptionPane.showMessageDialog(null,"密码修改失败");
                }
                else {
                    System.out.println("密码已修改");
                    JOptionPane.showMessageDialog(null,"密码已修改,请重新登录");
                    jFrame.dispose();
                }
            }
        });

        return mainPanel;

    }
}
